#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.basic.module.user.service.impl;

import ${package}.basic.module.group.mapper.GroupMapper;
import ${package}.basic.module.role.mapper.RoleMapper;
import ${package}.basic.module.user.mapper.UserMapper;
import ${package}.basic.module.user.service.UserService;
import ${package}.basic.module.userunionrole.mapper.UserUnionRoleMapper;
import ${package}.common.bean.po.Group;
import ${package}.common.bean.po.Role;
import ${package}.common.bean.po.User;
import ${package}.common.bean.po.UserUnionRole;
import ${package}.common.bean.vo.Constraint;
import ${package}.common.bean.vo.QueryBean;
import ${package}.common.bean.vo.UpdateUserVo;
import ${package}.common.component.service.CodeService;
import ${package}.common.emum.ConstEnum;
import ${package}.common.emum.UserStatusEnum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description: 无法补充
 *
 * @author wupanhua
 * @date 2019/8/6 15:28
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserServiceImpl implements UserService {

	/**
	 * 用户Mapper
	 */
	private final  UserMapper userMapper;
	/**
	 * 角色Mapper
	 */
	private final  RoleMapper roleMapper;
	/**
	 * 用户角色Mapper
	 */
	private final  UserUnionRoleMapper userUnionRoleMapper;
	/**
	 * 组织Mapper
	 */
	private final  GroupMapper groupMapper;


	private final CodeService codeService;


	/**
	 * Description:
	 * <不分页获取所有用户>
	 *
	 * @return java.util.List<User>
	 * @author wupanhua
	 * @date 11:39 2019/8/7
	 **/
	@Override
	public List<User> findAllUser() {
		return userMapper.findAllUser();
	}

	/**
	 * Description:
	 * <根据用户邮箱和密码查找到用户>
	 *
	 * @param user 1
	 * @return User
	 * @author wupanhua
	 * @date 11:39 2019/8/7
	 **/
	@Override
	public User findUserByEamilAndPassword(User user) {
		return userMapper.findUserByEmailAndPassword(user);
	}

	/**
	 * Description:
	 * <获得用户数据列表>
	 *
	 * @param queryBean 1
	 * @return com.github.pagehelper.PageInfo<User>
	 * @author wupanhua
	 * @date 11:39 2019/8/7
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class)
	public PageInfo<User> queryUserListByLimit(QueryBean queryBean) {

		Constraint constraint = Constraint.build()
				.putField("user.status")
				.putOp(Constraint.LOPERATE.IN.getOperation())
				.putValus(Boolean.TRUE, UserStatusEnum.ENABLED.getCode(), UserStatusEnum.EMAIL_UNVERIFIED.getCode(), UserStatusEnum.PHONE_UNVERIFIED.getCode(), UserStatusEnum.DISABLE.getCode())
				.putValueType(Constraint.DATATYPE.STRING.getType());
		queryBean.and(constraint);

		Page<User> page = PageMethod.startPage(queryBean.getCurrent(), queryBean.getPageSize());
		List<User> users = userMapper.queryUserList(queryBean);

		// 封装角色
		if (CollectionUtils.isNotEmpty(users)) {
			List<UserUnionRole> unrs = roleMapper.findUserRoleByUserList(users);
			Map<Long, List<UserUnionRole>> unrMap = unrs.stream().collect(Collectors.groupingBy(UserUnionRole::getUserId));
			for (User user : users) {
				List<UserUnionRole> userUnionRoles = unrMap.get(user.getId());
				if(CollectionUtils.isNotEmpty(userUnionRoles)){
					user.setRoleArrayList(userUnionRoles.stream().map(UserUnionRole::getRole).collect(Collectors.toList()));
				}

				//查询到用户的所属机构
				user.setGroupArrayList(new ArrayList<>());
				//找到所属机构链，便于显示层级关系
				if (user.getGroupId() != null) {
					Group group = groupMapper.getGroupById(user.getGroupId());
					while (group != null && !group.getId().equals(group.getParentId())) {
						user.getGroupArrayList().add(group);
						group = groupMapper.getGroupById(group.getParentId());
					}
				}
			}
		}

		return new PageInfo<>(page);
	}

	/**
	 * Description:
	 * <新增用户>
	 *
	 * @param user 1
	 * @author wupanhua
	 * @date 11:42 2019/8/7
	 **/
	@Override
	public void addUser(User user) {
		userMapper.addUser(user);
	}

	/**
	 * Description:
	 * <根据主键删除用户, 同时移除用户角色>
	 *
	 * @param id 1
	 * @author zhangwenyi
	 * @date 11:43 2019/8/7
	 **/
	@Override
	public void deleteUser(Long id) {

		//  物理删除用户
		userMapper.deleteUser(id);
		// 删除用户关联角色
		userUnionRoleMapper.removeByUserId(id);

	}

	/**
	 * Description:
	 * <禁用/启用用户>
	 *
	 * @param user 1
	 * @author pig
	 * @date 11:43 2019/8/7
	 **/
	@Override
	public void disableOrEnableUser(User user) {
		// 判断传来的状态更新为相反状态
		if (user.getStatus().intValue() == UserStatusEnum.ENABLED.getCode().intValue()) {
			user.setStatus(UserStatusEnum.DISABLE.getCode());
		} else {
			user.setStatus(UserStatusEnum.ENABLED.getCode());
		}

		userMapper.updateUserStatus(user.getId(), user.getStatus());
	}

	/**
	 * Description:
	 * <修改用户状态>
	 *
	 * @param user 1
	 * @author ZMF
	 * @date 16:27 2021/3/16
	 **/
	@Override
	public void updateUserStatus(UpdateUserVo user) {
		if(null!=user.getId() && null!=user.getStatus()) {
			userMapper.updateUserStatus(user.getId(), user.getStatus());
		}
	}

	/**
	 * Description:
	 * <根据id查询用户信息>
	 *
	 * @param id 1
	 * @return User
	 * @author pig
	 * @date 11:44 2019/8/7
	 **/
	@Override
	public User queryUserById(Long id) {
		return userMapper.queryUserById(id);
	}

	/**
	 * Description:
	 * <根据id修改用户信息>
	 *
	 * @param user 1
	 * @author pig
	 * @date 11:44 2019/8/7
	 **/
	@Override
	public void updateUserById(UpdateUserVo user) {
		userMapper.updateUserById(user);
	}

	/**
	 * Description:
	 * <根据主键重置用户密码>
	 *
	 * @param keys 1
	 * @author pig
	 * @date 11:44 2019/8/7
	 **/
	@Override
	public void resetUserPassByKey(Long[] keys) {
		String defaultPassword = ConstEnum.DEFAULT_PASSWORD.getNickName();
		String pwd = new BCryptPasswordEncoder().encode(defaultPassword);
		userMapper.resetUserPassByKey(pwd, keys);
	}

	/**
	 * Description:
	 * <批量删除用户>
	 *
	 * @param keys 1
	 * @author pig
	 * @date 11:45 2019/8/7
	 **/
	@Override
	public void removeUsersByKeys(List<Long> keys) {

		// 清空用户拥有的角色
		userUnionRoleMapper.removeUserUnionRolesByUserKeys(keys);

		// 将用户状态置为删除
		userMapper.updateUsersStatusDeleteByKeys(keys);
	}

	/**
	 * Description:
	 * <查询账户是否存在>
	 *
	 * @param username 1
	 * @param id       2
	 * @return java.lang.Boolean
	 * @author pig
	 * @date 11:45 2019/8/7
	 **/
	@Override
	public Boolean userVerifyUserId(String username, Long id) {

		if (id == null) {
			return CollectionUtils.isEmpty(userMapper.findUserByUserId(username));
		} else {
			return CollectionUtils.isEmpty(userMapper.findUserByNameOrNotInId(new User(id, username)));
		}
	}

	/**
	 * Description:
	 * <根据用户主键获取用户信息>
	 *
	 * @param user 1
	 * @return User
	 * @author 吴盼华
	 * @date 11:46 2019/8/7
	 **/
	@Override
	public User findUserById(User user) {
		user = userMapper.queryUserById(user.getId());
		List<Role> roles = roleMapper.findRolesByUserKey(user.getId());
		user.setRoleArrayList(roles);
		return user;
	}

	/**
	 * Description:
	 * <根据用户名查询用户信息>
	 *
	 * @param username 1
	 * @return User
	 * @author ywh
	 * @date 11:46 2019/8/7
	 **/
	@Override
	public User findUserByUsername(String username) {
		return userMapper.selectByUserName(username);
	}

}
